home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c-part2 / 10193 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  1.7 KB

  1. Path: mayne.ugrad.cs.ubc.ca!not-for-mail
  2. From: c2a192@ugrad.cs.ubc.ca (Kazimir Kylheku)
  3. Newsgroups: comp.lang.c
  4. Subject: Re: How to read a STRING from file?
  5. Date: 15 Mar 1996 14:28:33 -0800
  6. Organization: Computer Science, University of B.C., Vancouver, B.C., Canada
  7. Message-ID: <4icquhINNt76@mayne.ugrad.cs.ubc.ca>
  8. References: <s3032089.13.314913E2@sparc13.ncu.edu.tw>
  9. NNTP-Posting-Host: mayne.ugrad.cs.ubc.ca
  10.  
  11. In article <s3032089.13.314913E2@sparc13.ncu.edu.tw>,
  12. Alexander PeaceLand <s3032089@sparc13.ncu.edu.tw> wrote:
  13. >How could I read a real string from the file?
  14. >I used to read string by fscanf(), but it seems not work when the string 
  15. >I want is like "This is a book" that with space within it.
  16. >Is there any function or easy way to read sentence from file?
  17.  
  18. You can read newline-terminated sequences as strings using fgets().
  19.  
  20. To read zero-terminated data from a file, you will probably want to use fgetc()
  21. to scan individual cahracters from the file until you detect a zero. Same with
  22. reading a sentence. If your criteria for what a sentence is define it as the
  23. shortest available sequence of characters terminated by a period, you can do it
  24. easily using:
  25.  
  26.     while(1) {        /* loop indefinitely    */
  27.         char c = fgetc(inputfile);    /* get next characte    */
  28.         if (c == EOF)            /* if end of file    */
  29.             break;
  30.                     /* else record the character    */
  31.  
  32.         *bufptr++ = c;    /* should check for buffer overflow     */
  33.                 /* or change the design to allow    */
  34.                 /* arbitrary length sentences        */
  35.         if (c == '.');    /* bail if at end of sentence        */
  36.             break;
  37.     }
  38.     *bufptr++ = '\0';    /* zero-terminate the string        */
  39.  
  40. Of course these criteria for a sentence are naive. An abbreviation such as Mr.
  41. in the middle of a sentence will defeat it easily. But it's about the best you
  42. can do with zero lookahead.
  43. -- 
  44.  
  45.